<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\enum\TokenEnum;
use app\model\AccountApplyDetailModel;
use app\model\AccountApplyModel;
use app\model\AccountDailyStatModel;
use app\model\AccountProductSalesmanModel;
use app\model\BatchCreateSchemaUriModel;
use app\model\BatchProjectContentModel;
use app\model\ClientAccountModel;
use app\model\ClientAccountTimeModel;
use app\model\ClientCashRateModel;
use app\model\ClientMaterialCostModel;
use app\model\ClientMaterialPicCostModel;
use app\model\CostTaskAccountModel;
use app\model\KsAdvertiserModel;
use app\model\MediaTokenModel;
use app\model\mongo\MongoKsUserVideoModel;
use app\model\mongo\MongoKsVideoDayReportModel;
use app\model\mongo\MongoOeVideoDayReportModel;
use app\model\mongo\MongoOeVideoModel;
use app\model\mongo\MongoQqVideoDayReportModel;
use app\model\mongo\MongoQqVideoModel;
use app\model\mongo\MongoVideoModel;
use app\model\ProductAccountTypeDailyStatModel;
use app\model\ProjectAccountModel;
use app\model\VideoDailyCostMaterialModel;
use app\model\VideoModel;
use app\model\VideoRelationModel;
use app\model\ZcStoreModel;
use app\model\ZcSubtasksMemberModel;
use app\model\ZcTaskModel;
use app\service\batch\BatchService;
use app\service\client\AccountService;
use app\service\fetch\kuaishou\ReportRecordCampaignService;
use app\service\material\MaterialCostService;
use app\service\ocean\TokenService;
use app\service\OeFetchService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;

class TestWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('test');
        $this->setDescription('test');
        //        $this->addArgument('media_id', Argument::REQUIRED, '媒体id');
        //        $this->addArgument('stat_date', Argument::REQUIRED, '日期');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $videos = (new MongoVideoModel())->select();
        foreach ($videos as $video) {
            (new MongoOeVideoModel())->where('signature', $video->getAttr('signature'))->update(['all_staff_id' => $video->getAttr('all_staff_id')]);
            (new MongoKsUserVideoModel())->where('signature', $video->getAttr('signature'))->update(['all_staff_id' => $video->getAttr('all_staff_id')]);
            (new MongoQqVideoModel())->where('signature', $video->getAttr('signature'))->update(['all_staff_id' => $video->getAttr('all_staff_id')]);

            (new MongoOeVideoDayReportModel())->where('signature', $video->getAttr('signature'))->update(['all_staff_id' => $video->getAttr('all_staff_id')]);
            (new MongoKsVideoDayReportModel())->where('signature', $video->getAttr('signature'))->update(['all_staff_id' => $video->getAttr('all_staff_id')]);
            (new MongoQqVideoDayReportModel())->where('signature', $video->getAttr('signature'))->update(['all_staff_id' => $video->getAttr('all_staff_id')]);
        }
        dd('ok');
        (new BatchCreateSchemaUriModel())
            ->where('media_id', CommonEnum::KS_MEDIA)
            ->whereIn('advertiser_id', ['13614434',
                '13618143',
                '13618144',
                '13618145',
                '13618146',
                '13618147',
                '13618148',
                '13618149',
                '13618150',
                '13618151',
                '14331977',
                '14331978',
                '14331979',
                '14331980',
                '14331981',
                '14331982',
                '14331983',
                '14331984',
                '14331985',
                '14331986',
                '14686862',
                '14686863',
                '14686864',
                '14686865',
                '14686866',
                '14686867',
                '14686868',
                '14686869',
                '14686870',
                '14686871',
                '15044507',
                '15044508',
                '15044509',
                '15044510',
                '15044511',
                '15044512',
                '15044513',
                '15044514',
                '15044515',
                '15044516',
                '15080923',
                '15080924',
                '15080925',
                '15080926',
                '15080927',
                '15080928',
                '15080929',
                '15080930',
                '15080931',
                '15080932',
                '15125148',
                '15125149',
                '15125150',
                '15125151',
                '15125152',
                '15125153',
                '15125154',
                '15125155',
                '15125156',
                '15125157',
                '15493618',
                '15493619',
                '15493620',
                '15493621',
                '15493622',
                '15493623',
                '15493624',
                '15493625',
                '15493626',
                '15493627',
                '16567606',
                '16568745',
                '16568741',
                '16568740',
                '16568739',
                '16568747',
                '16568746',
                '16568744',
                '16568743',
                '16568742',
                '16770776',
                '16770781',
                '16770779',
                '16770782',
                '16770780',
                '16770778',
                '16770775',
                '16770783',
                '16770777',
                '16770774',
                '16774501',
                '16775740',
                '16775738',
                '16775737',
                '16775736',
                '16775734',
                '16775733',
                '16775732',
                '16775739',
                '16775735',
                '16878210',
                '16878209',
                '16878208',
                '16878207',
                '16878206',
                '17421955',
                '17421958',
                '17421952',
                '17421954',
                '17421960',
                '17421959',
                '17421956',
                '17421953',
                '17421957',
                '17421961',
                '19875555',
                '19875548',
                '19875553',
                '19875550',
                '19875549',
                '19875554',
                '19875552',
                '19875551',
                '19875557',
                '19875556',
                '20138353',
                '20141133',
                '20141138',
                '20141134',
                '20141130',
                '20141131',
                '20141136',
                '20141132',
                '20141135',
                '20141137',
                '20928086',
                '20928092',
                '20928091',
                '20928089',
                '20928085',
                '20928083',
                '20928087',
                '20928084',
                '20928090',
                '20928088',
                '21859421',
                '21859426',
                '21859424',
                '21859422',
                '21859420',
                '21859418',
                '21859417',
                '21859425',
                '21859419',
                '21859423',
                '21859539',
                '21859535',
                '21859534',
                '21859543',
                '21859537',
                '21859542',
                '21859541',
                '21859536',
                '21859538',
                '21859540'])
            ->where('material_id', 'buZqZ')
            ->field(true)
            ->chunk(200, function ($items) {
                if (! count($items)) {
                    return false;
                }

                $key = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['batch_ks_schema_material'];
                $redis = Cache::store('redis')->handler();
                foreach ($items as $v) {
                    $t = $v->getAttr('advertiser_id') . '|||' . $v->getAttr('type') . '|||' . $v->getAttr('material_id');
                    $this->getOutputMessage($v->getKey() . '~~~' . $t);
                    $redis->lPush($key, $t);
                }
            });

        $this->getOutputMessage('成功');
        exit;

        $advertiserIds = ClientAccountModel::where('media_id', 1)->column('id');
        foreach ($advertiserIds as $v) {
            $video = Db::connect('mongodb')->table('habo_oe_video')->where('account_id', $v)->select();
            foreach ($video as $item) {
                if (strpos(strval($item['create_time']), '-') !== false) {
                    $res = Db::connect('mongodb')->table('habo_oe_video')
                        ->where('_id', $item['_id'])->update(['create_time' => strtotime($item['create_time'])]);
                    if ($res) {
                        echo $v . '-' . $item['material_id'] . '成功' . PHP_EOL;
                    }
                }
            }
        }
        echo 'ok!';
        exit;

        $advertiserIds = KsAdvertiserModel::field('advertiser_id,user_id')
//            ->where('id', '>', 17409)
            ->select();
        foreach ($advertiserIds as $v) {
            $accountId = ClientAccountModel::where('advertiser_id', $v['advertiser_id'])->value('id');
            if ($accountId) {
                $res = Db::connect('mongodb')->table('habo_ks_pic_day_old_report')->where('account_id', $accountId)
//                    ->where('stat_date', 20231023)
                    ->update(['user_id' => $v['user_id']]);
                if ($res) {
                    echo $accountId . 'old更新成功' . PHP_EOL;
                }
                $res = Db::connect('mongodb')->table('habo_ks_pic_day_report')->where('account_id', $accountId)
                    ->update(['user_id' => $v['user_id']]);
                if ($res) {
                    echo $accountId . 'new更新成功' . PHP_EOL;
                }
            }
        }
        echo 'ok!';
        exit;

        $redis = Cache::store('redis')->handler();
        $ids = BatchProjectContentModel::whereIn('project_id', [14399])
            ->where('status', 0)
            ->where('content_level', 2)->column('id');
        foreach ($ids as $id) {
            $redis->rPush('task:batch:ks:unit:list', $id);
        }
        echo 'ok';
        exit;

        $data = Db::name('oe_batch_project_template')->select();
        foreach ($data as $v) {
            $title = explode(',', $v['title']);
            $title = json_encode($title, JSON_UNESCAPED_UNICODE);
            Db::name('oe_batch_project_template')->where('id', $v['id'])->update(['title' => $title]);
        }
        echo 'ok';
        exit;

        $contentId = BatchProjectContentModel::whereIn('project_id', [7998, 7997, 7996, 7993, 7991, 7990])
            ->where('content_level', 3)->where('status', 0)->column('id');
        BatchService::pushKsMaterialList($contentId);
        echo 'ok';
        exit;

        $statDate = intval($input->getArgument('stat_date'));

        $res = (new CostTaskAccountModel())->where('stat_date', $statDate)->delete();
        if ($res <= 0) {
            $output->writeln('删除失败！');
            return;
        }
        $output->writeln('删除成功！');
        return;
        $arr = [
            '16770779',
            '16770782',
            '16770780',
            '16770778',
            '16770775',
            '16770776',
            '16770781',
        ];
        foreach ($arr as $a) {
            echo $a . '开始' . PHP_EOL;
            ReportRecordCampaignService::getCampaign($a, 2);
            echo $a . '结束' . PHP_EOL;
        }

        exit;
        $data = ClientMaterialPicCostModel::where('media_id', 5)->where('stat_date', 20230726)->select()->toArray();
        foreach ($data as $v) {
            $rate = ClientCashRateModel::where('client_id', $v['client_id'])->where('date_time', 20230726)->where('media_id', 5)->value('valid_rate');
            if ($rate) {
                $cash = $v['cost'] * $rate;
                if (ClientMaterialPicCostModel::where('id', $v['id'])->update(['cash_cost' => $cash])) {
                    echo $v['signature'] . '成功' . PHP_EOL;
                } else {
                    echo $v['signature'] . '失败' . PHP_EOL;
                }
            }
        }

        echo 'ok';
        exit;
        $data = ClientMaterialCostModel::where('media_id', 5)->where('stat_date', 20230726)->select()->toArray();
        foreach ($data as $v) {
            $rate = ClientCashRateModel::where('client_id', $v['client_id'])->where('date_time', 20230726)->where('media_id', 5)->value('valid_rate');
            if ($rate) {
                $cash = $v['cost'] * $rate;
                if (ClientMaterialCostModel::where('id', $v['id'])->update(['cash_cost' => $cash])) {
                    echo $v['signature'] . '成功' . PHP_EOL;
                } else {
                    echo $v['signature'] . '失败' . PHP_EOL;
                }
            }
        }

        echo 'ok';
        exit;

        $ids = BatchProjectContentModel::where('project_id', 4057)->where('content_level', 3)->column('id');
        BatchService::pushKsMaterialList($ids);
        echo 'ok';
        exit;

        echo AccountService::getToken(2, '17134619');
        exit;

        $redis = Cache::store('redis')->handler();
        $ids = BatchProjectContentModel::where('project_id', 168)->where('status', 0)->where('content_level', 3)->column('id');
        foreach ($ids as $id) {
            $redis->rPush('task:batch:ks:creative:list', $id);
        }
        echo 'ok';
        exit;
        echo AccountService::getToken(2, '9948773', '', 1);
        exit;
        $account = ClientAccountModel::where('id', '>', 32638)->select();
        foreach ($account as $v) {
            if (strpos($v['advertiser_id'], 'del')) {
                continue;
            }
            $data = [
                'company_id' => $v['company_id'],
                'client_id' => $v['client_id'],
                'account_id' => $v['id'],
                'advertiser_id' => $v['advertiser_id'],
                'media_id' => $v['media_id'],
                'start_date' => date('Ymd', $v['add_time']),
                'end_date' => 20241231,
            ];
            ClientAccountTimeModel::create($data);
        }
        echo 'ok';
        exit;
        $redis = Cache::store('redis')->handler();
        $advs = [23903968, 29811800, 30119862, 30297681, 30298044, 30298098, 30298099, 30298102, 30298113, 30298117, 30298121, 30298124, 30298126, 30298127, 30298167, 30298176, 30874653];
        foreach ($advs as $v) {
            $redis->rPush('task:qq_video_recall', $v . '_0_1122');
            $redis->rPush('task:qq_pic_recall', $v . '_0_1122');
        }
        echo 'ok';
        exit;

        $advertiserId = '1758584357094413';
        $res = OeFetchService::fetchAppExtend($advertiserId);
        dump($res);
        exit;

        $account = ProductAccountTypeDailyStatModel::where('id', '>', 0)
            ->group('product_id,account_type,media_id')
            ->field('product_id,account_type,media_id')
            ->select();
        foreach ($account as $v) {
            $xs = AccountProductSalesmanModel::where('product_id', $v['product_id'])
                ->where('media_id', $v['media_id'])
                ->where('account_type', $v['account_type'])
                ->find();
            if ($xs) {
                ProductAccountTypeDailyStatModel::where('product_id', $v['product_id'])
                    ->where('media_id', $v['media_id'])
                    ->where('account_type', $v['account_type'])->update(['xs_id' => $xs['xs_id'] ? $xs['xs_id'] : 0, 'zl_id' => $xs['zl_id'] ? $xs['zl_id'] : 0]);
            }
        }
        echo 'done';
        exit;

        $account = AccountDailyStatModel::where('id', '>', 0)->group('advertiser_id')->field('account_id,advertiser_id')->select();
        foreach ($account as $v) {
            $applyId = AccountApplyDetailModel::where('advertiser_id', $v['advertiser_id'])->value('apply_id');
            if ($applyId) {
                $productId = AccountApplyModel::where('id', $applyId)->value('product_id');
                if ($productId) {
                    AccountDailyStatModel::where('account_id', $v['account_id'])->update(['product_id' => $productId]);
                }
            }
        }
        echo 'ok';
        exit;
        $mediaId = [2, 5];
        $date = [
            20230301, 20230302, 20230303, 20230304, 20230305, 20230306, 20230307, 20230308,
        ];
        foreach ($date as $d) {
            foreach ($mediaId as $m) {
                $res = MaterialCostService::cacheVideoCost((int) $d, (int) $m);
                if ($res) {
                    echo $d . '-' . $m . ' OK' . PHP_EOL;
                }
            }
        }
        echo 'done!';

        $date = createDateRange('2023-03-01', '2023-03-08');
        foreach ($date as $d) {
            for ($i = 0; $i <= 9; ++$i) {
                $res = MaterialCostService::cacheVideoAllVersionCost($d, (int) $i);
                if ($res) {
                    echo 'version:' . $d . '-' . $i . ' OK' . PHP_EOL;
                }
            }
        }
        echo 'done!';
        exit;

        $token = MediaTokenModel::where('media_id', 1)->select();
        $advIds = Db::name('crontab_task_bad_log')->where('id', '>=', 56845)->where('id', '<=', 57033)->group('advertiser_id')->column('advertiser_id');
        foreach ($advIds as $advId) {
            $account = ClientAccountModel::where('advertiser_id', $advId)->find();
            foreach ($token as $v) {
                TokenService::refreshAdv($v, $account);
            }
        }
        exit;
        $allAcount = ClientAccountModel::where('account_type', 1)
            ->where('')
            ->where('company_id', 1)
            ->field('id,client_id')
            ->select();
        $is = ProjectAccountModel::column('project_id');
        foreach ($allAcount as $v) {
            if (! in_array($v['id'], $is)) {
                $data = [
                    'project_id' => 43,
                    'client_id' => $v['client_id'],
                    'account_id' => $v['id'],
                ];
                ProjectAccountModel::create($data);
            }
        }
        echo 'ok';
        exit;
        $videos = VideoDailyCostMaterialModel::where('client_id', 0)->select();
        foreach ($videos as $video) {
            // 查询客户id
            $clientId = ClientMaterialCostModel::where('signature', $video['signature'])->value('client_id');
            if ($clientId) {
                VideoDailyCostMaterialModel::where('id', $video['id'])->update(['client_id' => $clientId]);
            }
        }
        echo 'ok';
        exit;
        $files = VideoRelationModel::order('id desc')->select();
        foreach ($files as $v) {
            $data = [];
            $video = VideoModel::where('file_id', $v['file_id'])->find();
            if ($video) {
                if ($video['task_id'] > 0) {
                    $task = ZcTaskModel::where('id', $video['task_id'])->find();
                    if ($task) {
                        $data['creative_team_id'] = $task['team_id'];
                        $store = ZcStoreModel::where('id', $task['store_id'])->find();
                        if ($store) {
                            $data['company_id'] = $store['company_id'];
                        }
                        // 查询任务参与人员
                        $staffIds = ZcSubtasksMemberModel::where('subtask_id', $video['subtask_id'])->group('user_id')->column('user_id');
                        if ($staffIds) {
                            foreach ($staffIds as $staffId) {
                                $data['staff_id'] = $staffId;
                                $isHas = VideoRelationModel::where('staff_id', $staffId)->where('file_id', $v['file_id'])->find();
                                if (! $isHas) {
                                    VideoRelationModel::create($data);
                                }
                            }
                            continue;
                        }
                    }
                } else {
                    $data['company_id'] = $video['company_id'];
                }
                VideoRelationModel::where('id', $v['id'])->update($data);
            }
        }
        echo 'ok';
        exit;
        $redis = Cache::store('redis')->handler();
        $advertiserIds = ClientAccountModel::alias('a')
            ->leftjoin(['habo_media_account' => 'b'], 'a.id=b.account_id')
            ->whereNull('b.id')
            ->where('media_id', 2)
            ->column('a.advertiser_id');
        foreach ($advertiserIds as $v) {
            $redis->rPush('token:account_list', $v);
        }
        exit;
        //        $mediaId = $input->getArgument('media_id');
        $redis = Cache::store('redis')->handler();
        $output->writeln('=======刷新token开始' . date('Y-m-d H:i:s', time()) . '=======');
        // oe
        $userId = Db::name('oe_user_account')->group('user_id')->column('user_id');
        foreach ($userId as $v) {
            $key = $v . TokenEnum::OE_TOKEN;
            $isHas = MediaTokenModel::where('redis_key', $key)->find();
            if (! $isHas) {
                $data = [
                    'media_app_id' => 0,
                    'media_id' => 1,
                    'access_token' => $redis->get($key),
                    'refresh_token' => $redis->get($v . TokenEnum::OE_REFRESH),
                    'content' => '',
                    'is_refresh' => 0,
                    'redis_key' => $key,
                ];
                MediaTokenModel::create($data);
            }
        }
        echo 'oe ok' . PHP_EOL;
        // ks
        $advertiserIds = Db::name('ks_advertiser')
            ->where('agent_id', 'notin', ['165898754', '165893525', '165893416'])
            ->group('advertiser_id')
            ->column('advertiser_id');
        foreach ($advertiserIds as $v) {
            $key = $v . TokenEnum::KS_NORMAL_TOKEN;
            $isHas = MediaTokenModel::where('redis_key', $key)->find();
            if (! $isHas) {
                $data = [
                    'media_app_id' => 0,
                    'media_id' => 2,
                    'access_token' => $redis->get($key),
                    'refresh_token' => $redis->get($v . TokenEnum::KS_NORMAL_REFRESH),
                    'content' => '',
                    'is_refresh' => 0,
                    'redis_key' => $key,
                ];
                MediaTokenModel::create($data);
            }
        }
        echo 'ks ok' . PHP_EOL;
        // qq
        //        $advertiserIds = Db::name('client_account')
        //            ->where('media_id', 5)
        //            ->group('advertiser_id')
        //            ->column('advertiser_id');
        //        foreach ($advertiserIds as $v) {
        //            $key = $v . TokenEnum::QQ_TOKEN;
        //            $isHas = MediaTokenModel::where('redis_key', $key)->find();
        //            if (! $isHas) {
        //                $data = [
        //                    'media_app_id' => 0,
        //                    'media_id' => 5,
        //                    'access_token' => $redis->get($key),
        //                    'refresh_token' => $redis->get($v . TokenEnum::QQ_REFRESH),
        //                    'content' => '',
        //                    'is_refresh' => 0,
        //                    'redis_key' => $key,
        //                ];
        //                MediaTokenModel::create($data);
        //            }
        //        }
        //        echo 'qq ok' . PHP_EOL;
        $output->writeln('=======刷新token结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }
}
